<?php

namespace App\Models\Rbac;


use App\Models\Common\CommonModel;

class GuardUser extends CommonModel {

    protected $table = 'guard_user';

    public function getRoles() {
        $roleIds = explode(',',$this->role_ids);
        return (new Role())->getRecordsByIds($roleIds);
    }

    public function hasPermissions() {
        $conditions = [
            'pid'=>0,
            'orderBy'=>['col'=>'sort', 'sort'=>'asc',]
        ];
        //如果登录的是SuperAdmin账户，那就拥有全部权限
        if($this->name == 'SuperAdmin'){
            $permissions = (new Permission())->getLst($conditions)->with(['children'])->get();
            //$permissions = $instance->getLst($conditions)->get();
        }else{
            $strPermissionIds = $this->getRoles()->pluck('permission_ids')->implode(',');
            $permissionIds = array_unique(array_filter(explode(',',$strPermissionIds)));
            $conditions['ids'] = $permissionIds;

            $permissions = Permission::where('pid',0)->whereIn('id',$conditions['ids'])->with(['children'=>function($q) use($conditions){
                $q->whereIn('id',$conditions['ids'])->orderBy('sort','desc');
            }])->get();
        }
        //return $this->listToTree($permissions);
        return $permissions;
    }

    /**
     * @deprecated 递归处理查询出来的权限树，暂时无用
     * @param $permissions
     * @return mixed
     */
    protected function listToTree(&$permissions){
        foreach ($permissions as $permission) {
            if(empty($permission->redirect))unset($permission->redirect);
            if(!empty($permission->children)){
                $this->listToTree($permission->children);
            }
        }
        return $permissions;
    }


    public function resetPassword($newPassword) {
        $this->password = md5($newPassword);
        return $this->save();
    }

    public function getGuardUserById(int $id):GuardUser {
        return $this->getRecordById($id);
    }

    public function getUserByName($name) {
        return $this->where('name',$name)->first();
    }

    public function getAdminUserByNameAndPwd($name,$password){
        $status = 1;
        return $this->getRecords(compact('name','password','status'))->first();
    }

    public function addLoginLog($ip,$device,$browser) {
        $info = compact('ip','device','browser');
        $info['user_id'] = $this->id;
        $info['last_login_time'] = date('Y-m-d H:i:s');
        /*$url = 'http://ip-api.com/json/'.$ip.'?lang=zh-CN';
        $ipAddress = makeRequest($url)['result'];
        $addr = json_decode($ipAddress,true);
        $address = $addr['regionName'].$addr['city'].'|'.$addr['lat'].','.$addr['lon'].'|'.$addr['query'];
        $info['address']  = $address;*/
        return LoginLog::create($info);
    }

}
